<template>
  <el-radio-group
    v-model="formData[prop]"
    @change="handleChange"
  >
    <el-radio-button value="" v-if="showAll">全部</el-radio-button>
    <el-radio-button
      v-for="item in options"
      :key="item.key"
      :value="item.key"
    >{{item.value}}</el-radio-button>
  </el-radio-group>
</template>

<script setup>
import { ref, inject, onMounted, watch } from 'vue';

const emit = defineEmits(['change']);
const props = defineProps({
  prop: {
    type: String,
    default: ''
  },
  options: [Array, String],
  showAll: {
    type: Boolean,
    default: () => false
  },
});
const formData = inject('formData');

const options = ref([]);

const init = (data) => {
  if (data.options) {
    if (Array.isArray(data.options)) {
      options.value = data.options;
    } else if (typeof data.options === 'string') {
      let optionList = [];
      data.options.split(',').forEach(item => {
        optionList.push({key: item, value: item});
      });
      options.value = optionList;
    }
  }
};

const handleChange = (event) => {
  emit('change', event);
};

watch(() => props, (data) => {
  init(data);
}, {deep: 1});

onMounted(() => {
  init(props);
});
</script>